package hello;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/greeting")
public class GreetingController {

	@Autowired
	private GreetingRepository gr;

	private static final String template = "Hello %s,welcome to spring boot!";
	private final AtomicLong counter = new AtomicLong();

	@RequestMapping("/hello")
	@Secured("ROLE_USER")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}

	@RequestMapping("/list")
	@Secured("ROLE_USER")
	public List<Greeting> list() {
		return (List<Greeting>) gr.findAll();
	}

	@RequestMapping("/add")
	@Secured("ROLE_ADMIN")
	public Greeting add(@RequestParam(value = "name", defaultValue = "World") String name) {
		return gr.save(new Greeting(counter.incrementAndGet(), String.format(template, name)));
	}

	@RequestMapping("/del")
	@Secured("ROLE_ADMIN")
	public void del(@RequestParam(value = "id", required = true) Long id) {
		gr.delete(id);
	}

	@RequestMapping("/update")
	@Secured("ROLE_ADMIN")
	public Greeting update(@RequestParam(value = "id", required = true) Long id,
			@RequestParam(value = "name", required = true) String name) {
		return gr.save(new Greeting(id, String.format(template, name)));
	}
}